package com.wzq.app.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.wzq.app.R;
import com.wzq.app.base.BaseActivity;
import com.wzq.app.manager.ActivityStackManager;
import com.wzq.app.ui.fragment.FirstFragment;
import com.wzq.app.ui.fragment.MineFragment;
import com.wzq.app.ui.fragment.SecondFragment;
import com.wzq.app.ui.widget.CatchableViewPager;
import com.wzq.app.utils.CrashUtils;
import com.wzq.app.utils.FilePathUtils;
import com.wzq.app.utils.MPermissionUtils;
import com.wzq.app.utils.permission.PermissionConstains;
import com.wzq.app.utils.permission.PermissionListener;
import com.wzq.app.utils.permission.PermissionUtils;
import com.wzq.app.utils.permission.PermissionsDispatcher;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 */

public class MainActivity extends BaseActivity implements PermissionListener {

    @BindView(R.id.main_viewpager)
    CatchableViewPager mainViewpager;
    @BindView(R.id.rb_home)
    RadioButton rbHome;
    @BindView(R.id.rb_change)
    RadioButton rbChange;
    @BindView(R.id.rb_mine)
    RadioButton rbMine;
    @BindView(R.id.rg_group)
    RadioGroup rgGroup;
    @BindView(R.id.main_footer)
    LinearLayout mainFooter;
    private FirstFragment firstFragment;
    private SecondFragment secondFragment;
    private MineFragment mineFragment;
    private ArrayList<Fragment> viewList;
    private int[] rbs = {R.id.rb_home, R.id.rb_change,
            R.id.rb_mine};

    private String TAG = "MainActivity";

    @Override
    public int getLayoutId() {
        return R.layout.main_activity;
    }

    @Override
    public void configView() {

        viewList = new ArrayList<>();//view数组
        firstFragment = new FirstFragment();
        secondFragment = new SecondFragment();
        mineFragment = new MineFragment();
        viewList.add(firstFragment);
        viewList.add(secondFragment);
        viewList.add(mineFragment);
        mainViewpager.setAdapter(new MainPagerAdapter(getSupportFragmentManager(), viewList));
        mainViewpager.setCurrentItem(0);
        mainViewpager.setOffscreenPageLimit(2);  //修改点  3

        rgGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                for (int i = 0; i < rbs.length; i++) {
                    if (rbs[i] != checkedId) continue;
                    //加载滑动
                    mainViewpager.setCurrentItem(i);
                }
            }
        });
        //ViewPager的点击事件 vp-rg互相监听：vp
        mainViewpager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                rgGroup.check(rbs[position]);
            }
        });
        //设置一个默认页
        rgGroup.check(rbs[0]);
    }

    @Override
    public void requestData() {

    }


    /**
     * @param requestCode 用于与startActivityForResult中的requestCode中值进行比较判断，是以便确认返回的数据是从哪个Activity返回的。
     * @param resultCode  (整数)由子Activity通过其setResult()方法返回。适用于多个activity都返回数据时，来标识到底是哪一个activity返回的值。
     * @param data        一个Intent对象，带有返回的数据。可以通过data.getXxxExtra( );方法来获取指定数据类型的数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        for (int i = 0; i < viewList.size(); i++) {
            viewList.get(i).onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 注意
            intent.addCategory(Intent.CATEGORY_HOME);
            this.startActivity(intent);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        PermissionsDispatcher.checkPermissions(this, PermissionConstains.PERMISSION_RESULT_CODE_LOCATION, this, Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION);
    }


    @Override
    public void onPermissionsDenied(Activity act, int requestCode, int[] grantResults, String... permissions) {
        switch (requestCode) {
            case PermissionConstains.PERMISSION_RESULT_CODE_LOCATION: {
                PermissionUtils.startAppSettings(mContext);
                break;
            }
            case PermissionConstains.PERMISSION_RESULT_CODE_WRITE_STORAGE: {
                ActivityStackManager.getInstance().AppExit(mContext);
                break;

            }

        }
    }

    @Override
    public void onPermissionsGranted(Activity act, int requestCode, int[] grantResults, String...
            permissions) {
        switch (requestCode) {
            case PermissionConstains.PERMISSION_RESULT_CODE_WRITE_STORAGE:
                CrashUtils.init(FilePathUtils.getCrashPath());
                break;
            default:
                break;

        }
    }

    @Override
    public void onShowRequestPermissionRationale(final Activity act, final int requestCode, boolean isShowRationale, final String... permissions) {
        String message = PermissionConstains.getMessage(requestCode);
        if (isShowRationale) {
//            DialogUtils.showInfo(mContext, message, new DialogUtils.MessageBoxHandler() {
//                @Override
//                public void commandHandler() {
            PermissionsDispatcher.requestPermissions(act, requestCode, permissions);
//                }
//            });
        } else {
            PermissionsDispatcher.requestPermissions(act, requestCode, permissions);
        }
    }

    @Override
    public void onPermissionsError(Activity act, int requestCode, int[] grantResults, String errorMsg, String... permissions) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionsDispatcher.onRequestPermissionsResult(this, requestCode, permissions, grantResults, this);
    }
}
